package service

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"math/rand"
	"strings"
	"time"

	"github.com/google/uuid"
	"github.com/wzh200x/hyperNexus/hyperNexusProtocol/commonProtocol"
	"github.com/wzh200x/webServer/constants"
	Server "github.com/wzh200x/webServer/server"
)

// 创建订单请求结构
type CreateOrderRequest struct {
	Data         string `json:"data" form:"data" binding:"required"`                 // 商品数据
	Goods        string `json:"goods" form:"goods" binding:"required"`               // 商品
	GoodsContent string `json:"goodsContent" form:"goodsContent" binding:"required"` // 商品内容
	GoodsPrice   int32  `json:"goodsPrice" form:"goodsPrice" binding:"required"`     // 商品价格
}

// 查询订单请求结构
type QueryOrderRequest struct {
	Status int32 `json:"status" form:"status" binding:"required"` // 订单状态
}

// 支付完成请求结构
type PayedOrderRequest struct {
	Order string `json:"order" form:"order" binding:"required"` // 订单号
}

// 发货请求结构
type ShipOrderRequest struct {
	Order string `json:"order" form:"order" binding:"required"` // 订单号
}

// 订单响应结构
type OrderResponse struct {
	ID                 int32  `json:"id"`                 // 订单ID
	HyperNexusAvatarId int64  `json:"hyperNexusAvatarId"` // 角色HyperNexusAvatarId
	Account            string `json:"account"`            // 账号
	AvatarId           int32  `json:"avatarId"`           // 角色ID
	Order              string `json:"order"`              // 订单号
	Data               string `json:"data"`               // 商品数据
	Status             int32  `json:"status"`             // 订单状态
	Goods              string `json:"goods"`              // 商品
	GoodsContent       string `json:"goodsContent"`       // 商品内容
	GoodsPrice         int32  `json:"goodsPrice"`         // 商品价格
	CreateTime         string `json:"createTime"`         // 创建时间
	UpdateTime         string `json:"updateTime"`         // 更新时间
}

// 订单查询响应结构
type OrderQueryResponse struct {
	Orders []*OrderResponse `json:"orders"` // 订单列表
}

// CreateOrder 创建订单
func CreateOrder(userID uint, username string, req CreateOrderRequest) (*OrderResponse, int, string) {
	// 获取DbAgentServerClient
	dbAgentClient := Server.ServerApp.DbAgentServerClient.GetClientProxy()

	// 查询账号是否存在
	accountQuery := commonProtocol.AccountQuery{
		AccountName: username,
	}
	account, queryErr := dbAgentClient.QueryAccount(accountQuery)
	if queryErr != nil {
		return nil, constants.ErrUnknown, "查询账号失败: " + queryErr.Error()
	}

	// 检查是否有角色
	if account.AvatarId <= 0 && account.HyperNexusAvatarId <= 0 {
		return nil, constants.ErrCharacterNotExist, "角色不存在"
	}

	// 查询角色信息
	avatarQuery := commonProtocol.AvatarQuery{
		AccountName:        username,
		AvatarId:           account.AvatarId,
		HyperNexusAvatarId: account.HyperNexusAvatarId,
	}
	avatar, avatarErr := dbAgentClient.QueryAvatar(avatarQuery)
	if avatarErr != nil {
		return nil, constants.ErrCharacterNotExist, "查询角色失败: " + avatarErr.Error()
	}

	// 生成唯一订单号
	orderNumber := generateOrderNumber()

	// 创建订单
	order := commonProtocol.Order{
		HyperNexusAvatarId: avatar.HyperNexusAvatarId,
		Account:            username,
		AvatarId:           avatar.ID,
		Order:              orderNumber,
		Data:               req.Data,
		Status:             0, // 初始状态为0，表示未支付
		Goods:              req.Goods,
		GoodsContent:       req.GoodsContent,
		GoodsPrice:         req.GoodsPrice,
	}

	// 调用DbAgentServer创建订单
	createdOrder, createErr := dbAgentClient.CreateOrder(order)
	if createErr != nil {
		return nil, constants.ErrOrderCreate, "创建订单失败: " + createErr.Error()
	}

	// 返回订单信息
	return &OrderResponse{
		ID:                 createdOrder.ID,
		HyperNexusAvatarId: createdOrder.HyperNexusAvatarId,
		Account:            createdOrder.Account,
		AvatarId:           createdOrder.AvatarId,
		Order:              createdOrder.Order,
		Data:               createdOrder.Data,
		Status:             createdOrder.Status,
		Goods:              createdOrder.Goods,
		GoodsContent:       createdOrder.GoodsContent,
		GoodsPrice:         createdOrder.GoodsPrice,
		CreateTime:         createdOrder.CreateTime,
		UpdateTime:         createdOrder.UpdateTime,
	}, 0, ""
}

// QueryOrdersByStatus 根据状态查询订单
func QueryOrdersByStatus(username string, status int32) (*OrderQueryResponse, int, string) {
	// 获取DbAgentServerClient
	dbAgentClient := Server.ServerApp.DbAgentServerClient.GetClientProxy()

	// 查询账号是否存在
	accountQuery := commonProtocol.AccountQuery{
		AccountName: username,
	}
	account, queryErr := dbAgentClient.QueryAccount(accountQuery)
	if queryErr != nil {
		return nil, constants.ErrUnknown, "查询账号失败: " + queryErr.Error()
	}

	// 检查是否有角色
	if account.AvatarId <= 0 && account.HyperNexusAvatarId <= 0 {
		return nil, constants.ErrCharacterNotExist, "角色不存在"
	}

	// 创建订单查询请求
	orderQuery := commonProtocol.OrderQuery{
		AccountName:        username,
		HyperNexusAvatarId: account.HyperNexusAvatarId,
	}

	// 调用DbAgentServer查询订单
	queryResult, queryOrderErr := dbAgentClient.QueryOrder(orderQuery)
	if queryOrderErr != nil {
		return nil, constants.ErrOrderQuery, "查询订单失败: " + queryOrderErr.Error()
	}

	// 过滤出符合状态的订单
	response := &OrderQueryResponse{
		Orders: make([]*OrderResponse, 0),
	}

	for _, order := range queryResult.Orders {
		if order.Status == status {
			response.Orders = append(response.Orders, &OrderResponse{
				ID:                 order.ID,
				HyperNexusAvatarId: order.HyperNexusAvatarId,
				Account:            order.Account,
				AvatarId:           order.AvatarId,
				Order:              order.Order,
				Data:               order.Data,
				Status:             order.Status,
				Goods:              order.Goods,
				GoodsContent:       order.GoodsContent,
				GoodsPrice:         order.GoodsPrice,
				CreateTime:         order.CreateTime,
				UpdateTime:         order.UpdateTime,
			})
		}
	}

	return response, 0, ""
}

// generateOrderNumber 生成唯一订单号
func generateOrderNumber() string {
	// 创建一个新的随机数生成器
	r := rand.New(rand.NewSource(time.Now().UnixNano()))

	// 1. 生成UUID
	uuidObj := uuid.New()
	uuidStr := uuidObj.String()

	// 2. 获取毫秒级时间戳
	timestamp := time.Now().UnixNano() / 1e6

	// 3. 生成两个随机数
	random1 := r.Intn(10000)
	random2 := r.Intn(1000000)

	// 4. 创建一个包含当前时间的哈希
	timeHash := createTimeHash(r)

	// 5. 组合所有元素
	baseOrderNumber := fmt.Sprintf("%d-%s-%04d-%06d-%s",
		timestamp,
		uuidStr[0:8], // 只使用UUID的一部分
		random1,
		random2,
		timeHash[0:6])

	// 6. 移除所有破折号，使订单号更简洁
	cleanOrderNumber := strings.ReplaceAll(baseOrderNumber, "-", "")

	// 7. 如果订单号太长，可以截取一部分
	if len(cleanOrderNumber) > 32 {
		cleanOrderNumber = cleanOrderNumber[0:32]
	}

	return cleanOrderNumber
}

// createTimeHash 创建基于当前时间的哈希值
func createTimeHash(r *rand.Rand) string {
	// 使用纳秒级时间戳和一些额外信息
	timeData := fmt.Sprintf("%d-%d-%d",
		time.Now().UnixNano(),
		r.Int63(),
		time.Now().Unix())

	// 计算MD5哈希
	hash := md5.Sum([]byte(timeData))
	return hex.EncodeToString(hash[:])
}

// UpdateOrderToPaid 将订单状态更新为已支付
func UpdateOrderToPaid(username string, orderNumber string) (*OrderResponse, int, string) {
	// 获取DbAgentServerClient
	dbAgentClient := Server.ServerApp.DbAgentServerClient.GetClientProxy()

	// 查询账号是否存在
	accountQuery := commonProtocol.AccountQuery{
		AccountName: username,
	}
	account, queryErr := dbAgentClient.QueryAccount(accountQuery)
	if queryErr != nil {
		return nil, constants.ErrUnknown, "查询账号失败: " + queryErr.Error()
	}

	// 检查是否有角色
	if account.AvatarId <= 0 && account.HyperNexusAvatarId <= 0 {
		return nil, constants.ErrCharacterNotExist, "角色不存在"
	}

	// 创建订单查询请求
	orderQuery := commonProtocol.OrderQuery{
		AccountName:        username,
		HyperNexusAvatarId: account.HyperNexusAvatarId,
		Order:              orderNumber,
	}

	// 调用DbAgentServer查询订单
	queryResult, queryOrderErr := dbAgentClient.QueryOrder(orderQuery)
	if queryOrderErr != nil {
		return nil, constants.ErrOrderQuery, "查询订单失败: " + queryOrderErr.Error()
	}

	// 检查是否找到订单
	if len(queryResult.Orders) == 0 {
		return nil, constants.ErrOrderQuery, "订单不存在"
	}

	// 获取订单
	order := queryResult.Orders[0]

	// 检查订单状态
	if order.Status == constants.OrderStatusPaid {
		return nil, constants.ErrOrderUpdate, "订单已支付"
	}

	// 更新订单状态为已支付
	order.Status = constants.OrderStatusPaid

	// 调用DbAgentServer更新订单
	updatedOrder, updateErr := dbAgentClient.UpdateOrder(*order)
	if updateErr != nil {
		return nil, constants.ErrOrderUpdate, "更新订单失败: " + updateErr.Error()
	}

	// 返回更新后的订单信息
	return &OrderResponse{
		ID:                 updatedOrder.ID,
		HyperNexusAvatarId: updatedOrder.HyperNexusAvatarId,
		Account:            updatedOrder.Account,
		AvatarId:           updatedOrder.AvatarId,
		Order:              updatedOrder.Order,
		Data:               updatedOrder.Data,
		Status:             updatedOrder.Status,
		Goods:              updatedOrder.Goods,
		GoodsContent:       updatedOrder.GoodsContent,
		GoodsPrice:         updatedOrder.GoodsPrice,
		CreateTime:         updatedOrder.CreateTime,
		UpdateTime:         updatedOrder.UpdateTime,
	}, 0, ""
}

// UpdateOrderToShipped 更新订单状态为已发货
func UpdateOrderToShipped(username string, orderNumber string) (*OrderResponse, int, string) {
	// 获取DbAgentServerClient
	dbAgentClient := Server.ServerApp.DbAgentServerClient.GetClientProxy()

	// 查询账号是否存在
	accountQuery := commonProtocol.AccountQuery{
		AccountName: username,
	}
	account, queryErr := dbAgentClient.QueryAccount(accountQuery)
	if queryErr != nil {
		return nil, constants.ErrUnknown, "查询账号失败: " + queryErr.Error()
	}

	// 检查是否有角色
	if account.AvatarId <= 0 && account.HyperNexusAvatarId <= 0 {
		return nil, constants.ErrCharacterNotExist, "角色不存在"
	}

	// 创建订单查询请求
	orderQuery := commonProtocol.OrderQuery{
		AccountName:        username,
		HyperNexusAvatarId: account.HyperNexusAvatarId,
		Order:              orderNumber,
	}

	// 调用DbAgentServer查询订单
	queryResult, queryOrderErr := dbAgentClient.QueryOrder(orderQuery)
	if queryOrderErr != nil {
		return nil, constants.ErrOrderQuery, "查询订单失败: " + queryOrderErr.Error()
	}

	// 检查是否找到订单
	if len(queryResult.Orders) == 0 {
		return nil, constants.ErrOrderQuery, "订单不存在"
	}

	// 获取订单
	order := queryResult.Orders[0]

	// 检查订单状态，必须是已付款状态
	if order.Status != constants.OrderStatusPaid {
		return nil, constants.ErrOrderUpdate, "订单未付款，无法发货"
	}

	// 更新订单状态为已发货
	order.Status = constants.OrderStatusShipped

	// 调用DbAgentServer更新订单
	updatedOrder, updateErr := dbAgentClient.UpdateOrder(*order)
	if updateErr != nil {
		return nil, constants.ErrOrderUpdate, "更新订单失败: " + updateErr.Error()
	}

	// 返回更新后的订单信息
	return &OrderResponse{
		ID:                 updatedOrder.ID,
		HyperNexusAvatarId: updatedOrder.HyperNexusAvatarId,
		Account:            updatedOrder.Account,
		AvatarId:           updatedOrder.AvatarId,
		Order:              updatedOrder.Order,
		Data:               updatedOrder.Data,
		Status:             updatedOrder.Status,
		Goods:              updatedOrder.Goods,
		GoodsContent:       updatedOrder.GoodsContent,
		GoodsPrice:         updatedOrder.GoodsPrice,
		CreateTime:         updatedOrder.CreateTime,
		UpdateTime:         updatedOrder.UpdateTime,
	}, 0, ""
}
